import { Injectable } from '@nestjs/common';
import { ServerException } from "@exceptions";
import { SendLoginCode } from "@dto/mail.dto";
import { HttpResTemplate, HttpResult } from "@libs/http.result";
import { ISendMailOptions, MailerService } from "@nestjs-modules/mailer";
import { getRandomNumber } from "@utils/number";
import { format } from "@utils/date";

@Injectable()
export class MailService {
    constructor(private readonly mailerService: MailerService) {
    }
    /**
     * 发送登录验证码
     * @param {string} mail
     */
    async sendLoginCode({ mail }: SendLoginCode): Promise<HttpResTemplate> {
        try {
            const code = getRandomNumber(6)
            const sendMailOption: ISendMailOptions = {
                to: mail,
                subject: 'NestAuth登录验证码',
                template: process.cwd() + '/templates/' + '/login-code',
                context: {
                    title: '成都xxxx科技有限公司',
                    user: mail,
                    code: code,
                    createTime: format(Date.now(), 'YYYY-MM-DD hh:mm'),
                    createUser: 'HR.Zhang'
                }
            }
            await this.mailerService.sendMail(sendMailOption) // 发起邮件
            return HttpResult.success()
        } catch(e) {
            throw new ServerException(e)
        }
    }
}
